const jsonfile = require('jsonfile');
module.exports = {
    '/':(req, res)=>{
        //type 0平台,1分类
        const {platform,type}=req.query
        const reqType=Number(type);
        let platformTags={}
        try {
            platformTags=jsonfile.readFileSync(`data/tag.json`)
        }catch {
            jsonfile.writeFileSync(`data/tag.json`, {})
        }
        if(reqType){
            if(!platform) return res.send({code:1,msg:'平台不能为空'});
            const tags=Object.keys(platformTags).filter(k=>/^classify_/.test(k) && new RegExp(`_${platform}`).test(k)).map(i=>i.replace('classify_','').replace(`_${platform}`,''))
            res.send({
                code:0,
                data:tags,
                msg:'请求成功'
            });
        }else {
            const platforms=Object.keys(platformTags).filter(k=>/^shop_/.test(k)).map(i=>({
                label:i.replace('shop_',''),
                value:platformTags[i].sign,
                type:platformTags[i].type,
                step:platformTags[i].step,
                isReady:platformTags[i].isReady || 0,
            }))
            res.send({
                code:0,
                data:platforms,
                msg:'请求成功'
            });
        }
    },
    '/set':(req, res)=>{
        const {platform,tag}=req.body
        if(!platform || !tag) return res.send({code:1,msg:'平台和分类不能为空'});
        const platformTags=jsonfile.readFileSync(`data/tag.json`)
        platformTags[`classify_${tag}_${platform}`]=platform
        jsonfile.writeFileSync(`data/tag.json`, platformTags)
        res.send({
            code: 0,
            msg: '操作成功',
        })
    },
    '/del':(req, res)=>{
        const {platform,tag}=req.body
        if(!platform || !tag) return res.send({code:1,msg:'平台和分类不能为空'});
        const platformTags=jsonfile.readFileSync(`data/tag.json`)
        if(platformTags[`classify_${tag}_${platform}`]){
            const listObject=jsonfile.readFileSync(`data/shop/${platform}.json`)
            if(listObject[tag] && listObject[tag].length){
                //存在禁止删除
                return res.send({
                    code: 1,
                    msg: '分类下有菜单，禁止删除',
                })
            }
            delete platformTags[`classify_${tag}_${platform}`]
            jsonfile.writeFileSync(`data/tag.json`,platformTags)
            res.send({
                code: 0,
                msg: '删除成功',
            })
        }else {
            res.send({
                code: 1,
                msg: '分类不存在',
            })
        }
    },
}
